﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace WindowsFormsApplicationPlatform
{
    /// <summary>
    /// 文件监控
    /// </summary>
    public class WorkFileWatchercs
    {
        /// <summary>
        /// PDF上传路径，物理地址
        /// </summary>
        string UploadPath = "D:\\BackPDf";

        /// <summary>
        /// 监控对象
        /// </summary>
        FileSystemWatcher watcher;
        /// <summary>
        /// 队列
        /// </summary>
        ConcurrentQueue<FileSystemEventArgs> fileQueue = new ConcurrentQueue<FileSystemEventArgs>();
        /// <summary>
        /// 
        /// </summary>
        ManualResetEvent mrePdf = new ManualResetEvent(false);
        /// <summary>
        /// 处理PDF队列
        /// </summary>
        Thread consumerThread;

        public void Start()
        {
            // 监控初始化，目录下PDF文件
            watcher = new FileSystemWatcher(UploadPath)
            {
                Filter = "*.pdf"
            };
            watcher.Changed += FileWatcherChanged;
            watcher.EnableRaisingEvents = true;


            // 启动处理程序
            consumerThread = new Thread(QueueConsumer)
            {
                IsBackground = true
            };
            consumerThread.Start();
        }

        /// <summary>
        /// 目录下文件变动触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void FileWatcherChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                if (e.ChangeType == WatcherChangeTypes.Deleted || File.Exists(e.FullPath) == false)
                {
                    return;
                }
                // 将文件变动加入到队列中
                fileQueue.Enqueue(e);
                mrePdf.Set();
            }
            catch (Exception ex)
            {

            }

        }
        /// <summary>
        /// 处理队列
        /// </summary>
        void QueueConsumer()
        {
            while (true)
            {
                try
                {
                    mrePdf.WaitOne();
                    mrePdf.Reset();
                    FileSystemEventArgs e;
                    while (fileQueue.TryDequeue(out e))
                    {
                        FileQueueInvoke(e);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }

         /// <summary>
        /// 检测到目录下有PDF变动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void FileQueueInvoke(FileSystemEventArgs e)
        {
            // 文件已经不存在
            if (e.ChangeType == WatcherChangeTypes.Deleted || File.Exists(e.FullPath) == false)
            {
                return;
            }

            System.Console.WriteLine("打印文件信息"+e.Name);
        }



    }
}
